<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select v-model="q.cate_id" placeholder="请选择分类" size="small">
              <el-option :key="item.id" v-for="item in cateList" :label="item.cate_name" :value="item.id"></el-option>

            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px;">
            <el-select v-model="q.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="loadArtList">筛选</el-button>
            <el-button type="info" size="small" @click="resetFrom">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button type="primary" size="small" class="btn-pub" @click="showPubDialog">发表文章</el-button>
      </div>

      <!-- 文章表格区域 -->
<el-table :data="ArtList" style="width: 100%;" border stripe>
  <el-table-column label="文章标题">
    <template v-slot:default="{row}">
<el-link type="primary" @click="showartlist(row.id)">{{row.title}}</el-link>
    </template>
  </el-table-column>
  <el-table-column label="分类" prop="cate_name"></el-table-column>
  <el-table-column label="发表时间">
      <template v-slot="{row}">
{{formData(row.pub_date)}}
      </template>
  </el-table-column>
  <el-table-column label="状态" prop="state"></el-table-column>
  <el-table-column label="操作">
      <template v-slot="{row}">
 <el-button type="danger" size="small" @click="removecate(row.id)">删除</el-button>
      </template>
  </el-table-column>
</el-table>
      <!-- 分页区域 -->
        <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="q.pagenum"
      :page-sizes="[2, 3, 5, 20]"
      :page-size="q.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    </el-card>
    <el-dialog
  title="添加文章"
  fullscreen
  :visible.sync="pubdialogVisible"
  width="30%">
<el-form :model="pubForm" :rules="pubFormRules" ref="pubFormRef" label-width="100px">
  <el-form-item label="文章标题" prop="title">
    <el-input v-model="pubForm.title" placeholder="请输入标题"></el-input>
  </el-form-item>
  <el-form-item label="文章分类" prop="cate_id">
    <el-select v-model="pubForm.cate_id" placeholder="请选择分类" style="width: 100%;">
       <el-option v-for="item in cateList"  :label="item.cate_name" :value="item.id" :key="item.id"></el-option>
    </el-select>
  </el-form-item>
  <el-form-item label="文章内容" prop="content" >
       <quill-editor v-model="pubForm.content" @blur="$refs.pubFormRef.validateField('content')"></quill-editor>
  </el-form-item>
  <el-form-item label="文章封面" prop="cover_img">
  <!-- 用来显示封面的图片 -->
  <img v-if="preview" :src="preview" alt="" class="cover-img" ref="imgRef" />
   <img v-else src="../../../assets/images/cover.jpg" alt="" class="cover-img" ref="imgRef" />
  <br />
  <!-- 文件选择框，默认被隐藏 -->
  <input type="file" style="display: none;" accept="image/*" ref="iptFile" @change="changeimg" />
  <!-- 选择封面的按钮 -->
  <el-button type="text" @click="$refs.iptFile.click()">+ 选择封面</el-button>
</el-form-item>
<el-form-item>
    <el-button type="primary" @click="submitfn('已发布')">发布</el-button>
     <el-button type="info" @click="submitfn('草稿')">存为草稿</el-button>
</el-form-item>
</el-form>
</el-dialog>
<!-- 页面弹出框 -->
<el-dialog
  title="文章预览"
  :visible.sync="ditalialogVisible"
  width="80%">
  <h1 class="title">{{ artDetail.title }}</h1>
  <div class="info">
    <span>作者：{{ artDetail.nickname || artDetail.username }}</span>
    <span>发布时间：{{ formData(artDetail.pub_date) }}</span>
    <span>所属分类：{{ artDetail.cate_name }}</span>
    <span>状态：{{ artDetail.state }}</span>
  </div>

  <!-- 分割线 -->
  <el-divider></el-divider>

  <!-- 文章的封面 -->
  <img :src="'http://www.liulongbin.top:3008' + artDetail.cover_img" alt="" />

  <!-- 文章的详情 -->
  <div v-html="artDetail.content" class="detail-box"></div>
</el-dialog>
  </div>
</template>

<script>
import dayjs from 'dayjs'
export default {
  name: 'ArtList',
  data () {
    return {
      // 查询参数对象
      q: {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      },
      pubdialogVisible: false,
      ditalialogVisible: false,
      artDetail: {},
      // currentPage4: 4,
      total: 0,
      pubForm: {
        title: '',
        cate_id: '',
        content: '',
        cover_img: '',
        state: ''
      },
      pubFormRules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 1, max: 30, message: '文章标题的长度为1-30个字符', trigger: 'blur' }
        ],
        cate_id: [
          { required: true, message: '请选择文章标题', trigger: 'change' }
        ],
        cover_img: [
          { required: true, message: '请选择图片', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入文章内容', trigger: 'blur' }
        ]
      },
      cateList: [],
      preview: '',
      ArtList: []
    }
  },
  methods: {
    removecate (id) {
      this.$confirm('是否删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete('/my/article/info', { params: { id } })
        // console.log(res)
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)
        // 最后重新渲染页面数据
        this.loadArtList()
      }).catch(() => {

      })
    },
    async showartlist (id) {
      const { data: res } = await this.$http.get('/my/article/info', { params: { id } })
      // console.log(res)
      // 根据结果来提醒用户
      if (res.code !== 0) return
      this.artDetail = res.data
      this.ditalialogVisible = true
    },
    resetFrom () {
      // 重置参数
      this.q = {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      }
      // 重新获取数据
      this.loadArtList()
    },
    showPubDialog () {
      this.pubdialogVisible = true
    },
    async  getcateList () {
      const { data: res } = await this.$http.get('/my/cate/list')
      //   console.log(res)
      this.cateList = res.data
    },
    changeimg (e) {
      const file = e.target.files[0]
      console.log('用户选择了头像', e)
      if (file) {
        this.pubForm.cover_img = file
        this.preview = URL.createObjectURL(file)
        this.$refs.pubFormRef.validateField('cover_img')
      } else {
        this.pubForm.cover_img = ''
        this.preview = ''
      }
    },
    submitfn (state) {
      this.pubForm.state = state
      this.$refs.pubFormRef.validate(async valid => {
        // console.log(valid)
        if (!valid) return
        const fd = new FormData()
        // 转换为二进制格式
        Object.keys(this.pubForm).forEach(k => fd.append(k, this.pubForm[k]))
        // 发送请求
        const { data: res } = await this.$http.post('/my/article/add', fd)
        // 提醒用户
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)
        // 关闭弹出框
        this.pubdialogVisible = false
        // 清空表单
        this.$refs.pubFormRef.resetFields()
        // 清空图片
        this.preview = ''
      })
    },
    async loadArtList () {
      const { data: res } = await this.$http.get('/my/article/list', {
        params: this.q
      })
      //   console.log(res)
      // 把数据存入数组中
      this.ArtList = res.data
      this.total = res.total
    },
    formData (data) {
      return dayjs(data).format('YYYY-MM-DD HH:mm:ss')
    },
    handleSizeChange (val) {
      // console.log(`每页 ${val} 条`)
      // 显示的是每页的条数
      this.q.pagesize = val
      // 让它显示从第一页开始
      this.q.pagenum = 1
      // 重新渲染页面数据
      this.loadArtList()
    },
    handleCurrentChange (val) {
      // val当前页面值
      // console.log(`当前页: ${val}`)
      // val是当前的页数
      this.q.pagenum = val
      // 重新渲染页面
      this.loadArtList()
    }
  },
  created () {
    this.getcateList()
    this.loadArtList()
  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}
.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}
/deep/ .ql-editor {
  min-height: 300px;
}
</style>
